/*
moxl - Modular XML Library
Copyright (c) 2007, Malcolm Sparks

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package moxl.dom.support;

import java.util.AbstractList;
import java.util.List;

import moxl.dom.MoxlElement;
import moxl.dom.MoxlNode;

public class MoxlNodeListMutatorGuard extends AbstractList<MoxlNode>
{
	private final List<MoxlNode> delegate;
	private final MoxlElement parent;

	public MoxlNodeListMutatorGuard(List<MoxlNode> nodes, MoxlElement parent)
	{
		if (nodes == null)
		{
			throw new IllegalArgumentException("nodes cannot be null");
		}
		if (parent == null)
        {
	        throw new IllegalArgumentException("parent cannot be null");
        }
		this.delegate = nodes;
		this.parent = parent;
	}

	@Override
	public void add(int index, MoxlNode node)
	{
		MoxlNodeList.replaceParentOnNode(node, parent);
		delegate.add(index, node);
	}
	
	@Override
	public MoxlNode get(int index)
	{
		return delegate.get(index);
	}

	@Override
	public int size()
	{
		return delegate.size();
	}

	@Override
	public MoxlNode remove(int index)
	{
		MoxlNode result = delegate.remove(index);
		result.setParent(null);
		return result;
	}

}
